import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
    // 用户信息
    const userInfo = ref({
        id: '',
        username: '',
        nickname: '',
        avatar: '',
        roles: [],
        permissions: []
    })

    // 登录状态
    const isLogin = ref(false)

    // 用户菜单数据
    const userMenus = ref([])

    // 动态路由
    const dynamicRoutes = ref([])

    // 设置用户信息
    const setUserInfo = (info) => {
        userInfo.value = info
        isLogin.value = true
    }

    // 清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {
            id: '',
            username: '',
            nickname: '',
            avatar: '',
            roles: [],
            permissions: []
        }
        isLogin.value = false
        userMenus.value = []
        dynamicRoutes.value = []
    }

    // 设置用户菜单
    const setUserMenus = (menus) => {
        userMenus.value = menus
    }

    // 设置动态路由
    const setDynamicRoutes = (routes) => {
        dynamicRoutes.value = routes
    }

    // 检查权限
    const hasPermission = (permission) => {
        return userInfo.value.permissions.includes(permission)
    }

    // 检查角色
    const hasRole = (role) => {
        return userInfo.value.roles.includes(role)
    }

    return {
        userInfo,
        isLogin,
        userMenus,
        dynamicRoutes,
        setUserInfo,
        clearUserInfo,
        setUserMenus,
        setDynamicRoutes,
        hasPermission,
        hasRole
    }
})
